//
//  JKFileExplorerDownloadTaskViewController.m
//  Baisi
//
//  Created by albert on 2019/1/14.
//  Copyright © 2019 安永博. All rights reserved.
//

#import "JKFileExplorerDownloadTaskViewController.h"
#import "JKFileExplorerDownloadTaskCell.h"
#import "JKFileExplorerDownloadItem.h"
#import "JKFileExplorerEngine.h"

static NSMutableArray *ItemList;
static NSMutableDictionary *ItemDict;

static NSMutableDictionary *TaskDict;

@interface JKFileExplorerDownloadTaskViewController () <UITableViewDataSource, UITableViewDelegate>

/** tableView */
@property (nonatomic, weak) UITableView *tableView;
@end

@implementation JKFileExplorerDownloadTaskViewController

+ (NSMutableDictionary *)itemDict{
    if (!ItemDict) {
        ItemDict = [NSMutableDictionary dictionary];
    }
    return ItemDict;
}

+ (NSMutableArray *)itemList{
    if (!ItemList) {
        ItemList = [NSMutableArray array];
    }
    return ItemList;
}

+ (NSMutableDictionary *)taskDict{
    if (!TaskDict) {
        TaskDict = [NSMutableDictionary dictionary];
    }
    return TaskDict;
}

+ (instancetype)addTaskWithUrl:(NSString *)url
                     directory:(NSString *)directory
                      fileName:(NSString *)fileName{
    
    if (!url | !directory || !fileName) { return nil; }
    
    JKFileExplorerDownloadItem *item = [[self itemDict] objectForKey:url];
    
    if (!item) {
        
        item = [[JKFileExplorerDownloadItem alloc] init];
        
        item.downloadUrl = url;
        item.fileDirectory = directory;
        item.fileName = fileName;
        item.filePath = [directory stringByAppendingPathComponent:fileName];
        
        [[self itemList] addObject:item];
        [[self itemDict] setObject:item forKey:url];
    }
    
    JKFileExplorerDownloadTaskViewController *vc = [[JKFileExplorerDownloadTaskViewController alloc] init];
    
    [vc startDownloadWithItem:item];
    
    return vc;
}

- (void)startDownloadWithItem:(JKFileExplorerDownloadItem *)item{
    
    if (!item) { return; }
    
    NSURLSessionDownloadTask *task = [[[self class] taskDict] objectForKey:item.downloadUrl];
    
    if (task) {
        
        switch (task.state) {
            case NSURLSessionTaskStateRunning:
            {
                
            }
                break;
            case NSURLSessionTaskStateSuspended:
            {
                [task resume];
            }
                break;
            case NSURLSessionTaskStateCanceling:
            case NSURLSessionTaskStateCompleted:
            {
                
                [[self class] removeWithUrl:item.downloadUrl];
            }
                break;
                
            default:
                break;
        }
        
        return;
    }
    
    task = [JKFileExplorerEngine downLoadFileWithUrl:item.downloadUrl directory:item.fileDirectory fileName:item.fileName progress:^(NSProgress *downloadProgress) {
        
        item.downloadProgress = downloadProgress.fractionCompleted;
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            !item.progressBlock ? : item.progressBlock(item);
        });
        
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        
        if (error) {
            
            return;
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:JKFileExplorerDidAddFileNotification object:nil userInfo:filePath ? @{JKFileExplorerFileOperateDestinationFilePathsKey : filePath.path} : nil];
        
        NSLog(@"下载成功: %@", response.URL);
    }];
    
    [task resume];
    
    [[[self class] taskDict] setObject:task forKey:item.downloadUrl];
}

+ (void)removeWithUrl:(NSString *)url{
    
    if (!url) { return; }
    
    JKFileExplorerDownloadItem *item = [[self itemDict] objectForKey:url];
    NSURLSessionDownloadTask *task = [[self taskDict] objectForKey:url];
    
    if (task) {
        
        [[self taskDict] removeObjectForKey:url];
    }
    
    if (item) {
        
        [[self itemDict] removeObjectForKey:url];
        
        if ([[self itemList] containsObject:item]) {
            
            [[self itemList] removeObject:item];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"下载列表";
    
    UITableView *tableView = [self tableViewWithStyle:(UITableViewStylePlain)];
    
    [self.view addSubview:tableView];
    
    _tableView = tableView;
    self.tipLabel.text = @"暂无任务";
    self.tipLabel.center = CGPointMake(self.tableView.frame.size.width * 0.5, self.tableView.frame.size.height * 0.382);
    [self.tableView insertSubview:self.tipLabel atIndex:0];
    
    [self.tableView registerClass:[JKFileExplorerDownloadTaskCell class] forCellReuseIdentifier:NSStringFromClass([JKFileExplorerDownloadTaskCell class])];
    
    [self loadTaskList];
}

- (void)loadTaskList{
    
    self.tipLabel.hidden = [[self class] itemList].count > 0;
    
    [self.tableView reloadData];
}

#pragma mark
#pragma mark - tableView数据源及代理

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[self class] itemList].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    JKFileExplorerDownloadTaskCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([JKFileExplorerDownloadTaskCell class])];
    
    if (cell == nil) {
        
        cell = [[JKFileExplorerDownloadTaskCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:NSStringFromClass([JKFileExplorerDownloadTaskCell class])];
    }
    
    if (indexPath.row < [[self class] itemList].count) {
        
        cell.item = [[[self class] itemList] objectAtIndex:indexPath.row];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableView *)tableViewWithStyle:(UITableViewStyle)style{
    
    CGFloat navigationBarHeight = JKIsIphoneX ? 88 : 64;
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, navigationBarHeight, self.view.width, self.view.height - navigationBarHeight) style:(style)];
    [self.view insertSubview:tableView atIndex:0];
    
    tableView.backgroundColor = nil;
    tableView.dataSource = self;
    tableView.delegate = self;
    
    tableView.rowHeight = 44;
    tableView.sectionFooterHeight = 0;
    tableView.sectionHeaderHeight = 0;
    
    tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, CGFLOAT_MIN)];
    tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, CGFLOAT_MIN)];
    
    tableView.scrollsToTop = YES;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    SEL selector = NSSelectorFromString(@"setContentInsetAdjustmentBehavior:");
    
    if ([tableView respondsToSelector:selector]) {
        
        IMP imp = [tableView methodForSelector:selector];
        void (*func)(id, SEL, NSInteger) = (void *)imp;
        func(tableView, selector, 2);
        
        // [tableView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2)];
    }
    
    return tableView;
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
